// crawler.js
import axios from 'axios';
import mysql from 'mysql2/promise';

// 数据库配置（需要修改为你的配置）
const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: '123456',  // 如果你设置了密码，请填入
  database: 'musiccenter'
};

// 爬取配置
const API_URL = 'https://c.y.qq.com/splcloud/fcgi-bin/fcg_get_diss_by_tag.fcg';
const PARAMS = {
  g_tk: '5381',
  loginUin: '0',
  hostUin: '0',
  format: 'json',
  inCharset: 'utf8',
  outCharset: 'utf-8',
  notice: '0',
  platform: 'yqq.json',
  needNewCode: '0',
  categoryId: '10000000',
  sortId: '5',
  sin: '0',
  ein: '19',  // 获取20条数据
  picmid: '1'
};

async function main() {
  // 创建数据库连接
  const conn = await mysql.createConnection(dbConfig);

  try {
    // 创建数据表（如果不存在）
    await conn.execute(`CREATE TABLE IF NOT EXISTS recommended (
      id INT AUTO_INCREMENT PRIMARY KEY,
      recommendImage VARCHAR(500) NOT NULL,
      recommendTitle VARCHAR(200) NOT NULL,
      recommendData INT NOT NULL
    )`);

    // 发送API请求
    const response = await axios.get(API_URL, {
      params: { ...PARAMS, rnd: Math.random() },
      headers: {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        'Referer': 'https://y.qq.com/'
      }
    });

    // 处理数据
    const playlists = response.data.data.list.slice(0, 20);
    const insertData = playlists.map(item => [
      item.imgurl ? item.imgurl.replace('/150/', '/300/') : '',  // 高清图片
      item.dissname || '',                                        // 标题
      item.playnum ? (parseInt(item.playnum.replace('万', '')) * (item.playnum.includes('万') ? 10000 : 1)) : 0 // 播放量
    ]);

    // 批量插入数据
    const [result] = await conn.query(
      'INSERT INTO recommended (recommendImage, recommendTitle, recommendData) VALUES ?',
      [insertData]
    );

    console.log(`成功插入 ${result.affectedRows} 条数据`);
  } catch (error) {
    console.error('运行出错:', error.message);
  } finally {
    await conn.end();
  }
}

main();
